package com.yimu.ymblog.jwt.handler;

import com.yimu.ymblog.common.enums.ResponseCodeEnum;
import com.yimu.ymblog.common.utils.Response;
import com.yimu.ymblog.jwt.exception.UsernameOrPasswordNullException;
import com.yimu.ymblog.jwt.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.warn("AuthenticationException: ", exception);
        if (exception instanceof UsernameOrPasswordNullException) {
            // 用户名或密码为空
            ResultUtil.fail(response, Response.fail(exception.getMessage()));
        } else if (exception instanceof BadCredentialsException) {
            // 用户名或密码错误
            ResultUtil.fail(response, Response.fail(ResponseCodeEnum.USERNAME_NOT_EXISTED_OR_PWD_ERROR));
        } else if (exception instanceof InternalAuthenticationServiceException) {
            // InternalAuthenticationServiceException是内部服务错误的异常，隐藏了具体异常
            // 需要通过getCause()获取具体异常名
            if (exception.getCause() instanceof DisabledException) {
                // 用户被禁用
                ResultUtil.fail(response, Response.fail(ResponseCodeEnum.USER_DISABLED));
            }
        }

        // 登录失败
        ResultUtil.fail(response, Response.fail(ResponseCodeEnum.LOGIN_FAIL));
    }
}